package logger

import (
	"easy-sys/base/entity"
	"easy-sys/sys/domain/log"
	"time"

	"github.com/gin-gonic/gin"
)

// 日志记录到文件
func LogToDb() gin.HandlerFunc {

	return func(c *gin.Context) {
		var sysLog log.SysLog
		// 开始时间
		startTime := time.Now()
		// 处理请求
		c.Next()
		// 结束时间
		endTime := time.Now()
		// 执行时间
		latencyTime := endTime.Sub(startTime)
		// 请求方式
		reqMethod := c.Request.Method
		// 请求路由
		reqUri := c.Request.RequestURI
		// 状态码
		statusCode := c.Writer.Status()
		// 请求IP
		clientIP := c.ClientIP()

		var userId, isExists = c.Get("userId")

		if isExists {
			sysLog.LogUserId = userId.(uint64)
		}

		sysLog.LogLatency = uint64(latencyTime.Milliseconds())
		sysLog.LogStart = entity.JSONTime(startTime)
		sysLog.LogEnd = entity.JSONTime(endTime)
		sysLog.CreateTime = entity.JSONTime(time.Now())
		sysLog.LogIp = clientIP
		sysLog.LogUri = reqUri
		sysLog.LogStatus = statusCode
		sysLog.LogMethod = reqMethod

		log.Save(sysLog)
	}
}
